package com.glls.sbdemo22.exception;

import com.glls.sbdemo22.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @date 2023/5/16
 * @desc
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 拦截业务异常，返回业务异常信息
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleBusinessError(BusinessErrorException ex) {
        String code = ex.getCode();
        String message = ex.getMessage();
        return R.error().code(Integer.parseInt(code)).message(message);
    }


    //除零异常处理器
    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleArithmeticException(ArithmeticException ex){

        return R.error().message(ex.getMessage());
    }

    //缺失参数异常处理器
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleArithmeticException(MissingServletRequestParameterException ex){
        return R.error().message("请检查下你的参数大哥");
    }



    //未知异常处理器
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleArithmeticException(Exception ex){
        // 把异常信息 输出在 控制台
        ex.printStackTrace();
        return R.error().message("我也不知道错哪了");
    }
}
